#!/usr/bin/python
#Script written by walkerworks 2016, with a little help from the Python programming community
import time
import RPi.GPIO as GPIO
from datetime import datetime
from Tkinter import *
import sys
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

root = Tk()
root.minsize(300,150)
root.title("8 Input Data Logger")
#root.geometry('340x670')

GPIO.setup(17, GPIO.IN)
GPIO.setup(27, GPIO.IN)
GPIO.setup(22, GPIO.IN)
GPIO.setup(23, GPIO.IN)
GPIO.setup(24, GPIO.IN)
GPIO.setup(10, GPIO.IN)
GPIO.setup(9, GPIO.IN)
GPIO.setup(25, GPIO.IN)

name_1 = StringVar()
name_2 = StringVar()
name_3 = StringVar()
name_4 = StringVar()
name_5 = StringVar()
name_6 = StringVar()
name_7 = StringVar()
name_8 = StringVar()
state_on = StringVar()
state_off = StringVar()

#This is where you can describe the Input function. i.e. replace "AA1" with "Heating valve"
name_1.set("AA1")
name_2.set("AA2")
name_3.set("AA3")
name_4.set("AA4")
name_5.set("AA5")
name_6.set("AA6")
name_7.set("AA7")
name_8.set("AA8")

#This is where you can describe the input state. i.e. ON/OFF, UP/DOWN, 0/1, Running/Stopped etc. 
state_on.set("ON")
state_off.set("OFF")


f=open('logger.log', 'a')
f.write("\n")
f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
f.write(" : Logger Started \n\n")    
f.close()


def tail_lines(filename,linesback=30,returnlist=0):

    avgcharsperline=75

    file = open('logger.log','r')
    while 1:
        try: file.seek(-1 * avgcharsperline * linesback,2)
        except IOError: file.seek(0)
        if file.tell() == 0: atstart=1
        else: atstart=0

        lines=file.read().split("\n")
        if (len(lines) > (linesback+1)) or atstart: break
        #The lines are bigger than we thought
        avgcharsperline=avgcharsperline * 1.3 #Inc avg for retry
    file.close()

    if len(lines) > linesback: start=len(lines)-linesback -1
    else: start=0
    if returnlist: return lines[start:len(lines)-1]

    out=""
    for l in lines[start:len(lines)-1]: out=out + l + "\n"
    return out


def write_1_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_1.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")    
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

def write_1_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_1.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

def write_2_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_2.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))


def write_2_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_2.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_3_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_3.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))    

    
def write_3_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_3.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

   
def write_4_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_4.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_4_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_4.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_5_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_5.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_5_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_5.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_6_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_6.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_6_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_6.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_7_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_7.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_7_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_7.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_8_up():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_8.get())
    f.write(" : ")
    f.write(state_on.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))

    
def write_8_dn():
# write data to file
    f=open('logger.log', 'a')
    f.write(datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')[:-3])
    f.write("  ")
    f.write(name_8.get())
    f.write(" : ")
    f.write(state_off.get())
    f.write("\n")  
    f.close()
    thirtylines.set(tail_lines('logger',30,0))
    

def input_1(input_pin):
    time.sleep(.1)
    if GPIO.input(17):
        write_1_up()
    else:
        write_1_dn()
        
def input_2(input_pin):
    time.sleep(.1)    
    if GPIO.input(27):
        write_2_up()
    else:
        write_2_dn()
        
def input_3(input_pin):
    time.sleep(.1)    
    if GPIO.input(22):
        write_3_up()
    else:
        write_3_dn()
        
def input_4(input_pin):
    time.sleep(.1)    
    if GPIO.input(23):
        write_4_up()
    else:
        write_4_dn()
        
def input_5(input_pin):
    time.sleep(.1)    
    if GPIO.input(24):
        write_5_up()
    else:
        write_5_dn()
        
def input_6(input_pin):
    time.sleep(.1)    
    if GPIO.input(10):
        write_6_up()
    else:
        write_6_dn()
        
def input_7(input_pin):
    time.sleep(.1)     
    if GPIO.input(9):
        write_7_up()
    else:
        write_7_dn()
        
def input_8(input_pin):
    time.sleep(.1)    
    if GPIO.input(25):
        write_8_up()
    else:
        write_8_dn()
        
GPIO.add_event_detect(17, GPIO.BOTH, bouncetime=200, callback=input_1)
GPIO.add_event_detect(27, GPIO.BOTH, bouncetime=200, callback=input_2)
GPIO.add_event_detect(22, GPIO.BOTH, bouncetime=200, callback=input_3)
GPIO.add_event_detect(23, GPIO.BOTH, bouncetime=200, callback=input_4)
GPIO.add_event_detect(24, GPIO.BOTH, bouncetime=200, callback=input_5)
GPIO.add_event_detect(10, GPIO.BOTH, bouncetime=200, callback=input_6)
GPIO.add_event_detect(9, GPIO.BOTH, bouncetime=200, callback=input_7)
GPIO.add_event_detect(25, GPIO.BOTH, bouncetime=200, callback=input_8)

# LabelFrame text could also include Site Name
labelframe = LabelFrame(root, text="Recent Events - Site Name")
labelframe.pack(fill="both", expand="yes")



thirtylines=StringVar()
thirtylines.set(tail_lines('logger',30,0))

left = Label(labelframe, textvariable=thirtylines, justify=LEFT, font=('helvetica', 12))

left.pack()
root.mainloop()